﻿using Com.OpenCode.Framework.Core;
using DevExpress.XtraBars;
using DevExpress.XtraBars.Ribbon;
using System.Drawing;
using System.Windows.Forms;

namespace Com.OpenCode.Framework.DevForm
{
    /// <summary>
    ///     Ribbon按钮
    /// </summary>
    public class RibbonButtonUI : BarButtonItem, IMenuVisible
    {
        private BarItemLink _BarItemLink;
        private ICommand _Command;

        #region 构造函数

        public RibbonButtonUI(BuildItemEventArgs args)
        {
            args.Plugin.Owner = this;
            PaintStyle = BarItemPaintStyle.CaptionGlyph;
            RibbonStyle = RibbonItemStyles.Large;
            Caption = args.Plugin.Properties.GetString("Text");
            Image image = null;
            if (args.Plugin.Properties.Exist("Image"))
            {
                string imagePath = System.IO.Path.Combine(args.Plugin.Addin.FileInfo.DirectoryName, args.Plugin.Properties.GetString("Image"));
                if (System.IO.File.Exists(imagePath))
                {
                    image = Image.FromFile(imagePath);
                }
            }
            else
            {
                image = IconDoozer.BulidItem(args.Plugin.Addin, args.Plugin.Properties.GetString("ImageId"));
            }
            if (image == null)
            {
                image = DevFormImage.Ribbon32;
            }
            LargeGlyph = image;
            Glyph = image;
            if (args.Plugin.Properties.Exist("Class"))
            {
                _Command = args.Plugin.Addin.Runtime.CreateObject(args.Plugin.Properties.GetString("Class")) as ICommand;
            }
            else
            {
                _Command = ClassDoozer.BulidItem(args.Plugin.Addin, args.Plugin.Properties.GetString("ClassId")) as ICommand;
            }
            if (args.Plugin.Properties.Exist("Shortcut"))
            {
                int shortcut = args.Plugin.Properties.GetInt("Shortcut");
                ItemShortcut = new BarShortcut((Shortcut) shortcut);
            }
            bool _BeginGroup;
            bool.TryParse(args.Plugin.Properties.Get("BeginGroup").ToString(), out _BeginGroup);
            _BarItemLink = (args.Owner as RibbonPageGroupUI).ItemLinks.Add(this);
             (args.Owner as RibbonPageGroupUI).Children.Add(this);
            _BarItemLink.BeginGroup = _BeginGroup;
        }

        #endregion

        public override bool Enabled
        {
            get
            {
                if (_Command != null)
                {
                    return _Command.Enable();
                }
                return false;
            }
            set { base.Enabled = value; }
        }

        protected override void OnClick(BarItemLink link)
        {
            _Command.Run();
        }

        public void CheckVisible()
        {
            
        }

    }
}